package models

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"time"

	//匿名引入mysql驱动
_ "github.com/go-sql-driver/mysql"
)

type User struct {
	Id   int    `orm:"auto"`
	Name string `orm:"column(name)"`
	Age  int    `orm:"column(age)"`
	Created time.Time `orm:"auto_now_add;type(datetime)"`
	Updated time.Time `orm:"auto_now;type(datetime)"`
}


var ORM orm.Ormer

func init() {
	// 注册 User 结构体模型
	orm.RegisterModel(new(User))
	orm.RegisterDataBase("default", "mysql", "root:123456@tcp(127.0.0.1:3307)/beego?charset=utf8")
	orm.SetMaxIdleConns("default", 30)

	ORM = orm.NewOrm()
}

func Add() {
	user := new(User)
	user.Name = "贾元春"
	user.Age = 25
	// 添加数据
	ORM.Insert(user)
}


func Delete() {
	var user = User{Id: 7}
	c, er := ORM.Delete(&user)
	if er != nil {
		fmt.Println(er)
	}
	fmt.Println(c)
}

func Update() {
	user := User{Id: 6, Name: "贾宝玉", Age: 24}
	//默认通过id 更新所有字段
	c, er := ORM.Update(&user)
	if er != nil {
		fmt.Println(er)
	}
	fmt.Println(c)

	user2 := User{Id: 8, Name: "史湘云", Age: 22}
	//根据id做条件只更新name字段
	ORM.Update(&user2, "name")
}


func Find() User {
	//user := &User{Id: 8}
	//通过主键id 查询
	//o.Read(user)

	user := &User{Name: "贾宝玉"}
	//非主键查询
	ORM.Read(user, "Name")

	fmt.Println(user)

	return *user
}